//自动化生成打包文件配置
// 导入fs模块
const fs = require('fs')
// 导入环境变量配置文件
const ENV_CONFIG = require('./src/common/js/config.js')
console.log('=========bulid Start=========')
console.log(ENV_CONFIG)

//项目main配置文件
const manifestPath = `${__dirname}/src/manifest.json`;

let Manifest = fs.readFileSync(manifestPath, {
	encoding: 'utf-8'
})

function replaceManifest(path, value) {
	const arr = path.split('.')
	const len = arr.length
	const lastItem = arr[len - 1]

	let i = 0
	let ManifestArr = Manifest.split(/\n/)

	for (let index = 0; index < ManifestArr.length; index++) {
		const item = ManifestArr[index]
		if (new RegExp(`"${arr[i]}"`).test(item)) ++i
		if (i === len) {
			const hasComma = /,/.test(item)
			ManifestArr[index] = item.replace(
				new RegExp(`"${lastItem}"[\\s\\S]*:[\\s\\S]*`),
				`"${lastItem}": ${value}${hasComma ? ',' : ''}`
			)
			break
		}
	}

	Manifest = ManifestArr.join('\n')
}

//config配置文件
const configPath = `${__dirname}/src/common/js/configTemp.js`;

let config = fs.readFileSync(configPath, {
	encoding: 'utf-8'
})

function replaceConfig(path, value) {
	const lastItem = path
	let configArr = config.split(/\n/)
	for (let index = 0; index < configArr.length; index++) {
		const item = configArr[index]
		if (new RegExp(`"${lastItem}"`).test(item)) {
			const hasComma = /,/.test(item)
			configArr[index] = item.replace(
				new RegExp(`"${lastItem}"[\\s\\S]*:[\\s\\S]*`),
				`"${lastItem}": ${value}${hasComma ? ',' : ''}`
			)
			break
		}
	}
	config = configArr.join('\n')
}

//pages配置文件
const pagesPath = `${__dirname}/src/pages.json`;

let pagesJson = fs.readFileSync(pagesPath, {
	encoding: 'utf-8'
})

//修改pages 全局默认标题
function replacePages(name=''){
	// 解析JavaScript对象
	const obj = eval(`(${pagesJson})`)
	// 修改指定键的值
	obj.globalStyle.navigationBarTitleText = name
	// 将修改后的JavaScript对象转换为字符串
	pagesJson = JSON.stringify(obj, null, 4);
}

// 读取环境变量内容
const envConfig = ENV_CONFIG[process.env.UNI_SCRIPT]

if(envConfig){
	for (let key in envConfig) {
		if (key == "appid") {
			replaceManifest('mp-weixin.appid', `"${envConfig[key]}"`)
		} else {
			if(key=='NAME'){
				replacePages(`${envConfig[key]}`)
			}
			replaceConfig(key,`"${envConfig[key]}"`)
		}
	}
	
	
	fs.writeFileSync(manifestPath, Manifest, {
		flag: 'w'
	})
	fs.writeFileSync(configPath, config, {
		flag: 'w'
	})
	
	fs.writeFileSync(pagesPath, pagesJson, {
		flag: 'w'
	})
}
console.log('=========bulid End=========')